package com.ethan.blog.common.handler;

import com.ethan.blog.common.exception.BaseException;
import com.ethan.blog.common.result.Result;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Ethan
 * @Time: 2024/5/26 11:37
 * @description: 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice// 全局异常处理器注解，用于捕获所有Controller抛出的异常
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理BaseException异常
     *
     * @param exception
     * @return 放回异常原因
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException exception) {
        log.error("异常信息：{}", exception.getMessage());
        return Result.error(exception.getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
//    @RequestBody
    public Result handleConstraintViolationException(ConstraintViolationException ex) {
        log.info("handleConstraintViolationException:{}", ex.getConstraintViolations());
        return Result.error(ex.getConstraintViolations().iterator().next().getMessage());
    }

    @ExceptionHandler(BindException.class)
//    @RequestBody
    public Result handleBindException(BindException ex) {
        // 获取所有错误字段及其错误信息
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        log.info("handleBindException:{}", fieldErrors);
        // 获取所有错误信息
        List<String> defaultMessages = fieldErrors
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        return Result.error(defaultMessages);
    }
}
